﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Data;
using System.Windows.Media;
using System.Windows.Media.Animation;

namespace Gmantis.Controls.DataGrid
{
    [TemplatePart(Name = "FilterCheckBox", Type = typeof(CheckBox))]
    public class DataGridCheckBoxFilter : Control, IDataGridFilter, IDataGridFilterUnity, INotifyPropertyChanged
    {
        // Fields
        internal CheckBox _elementFilterCheckBox;
        private DataGridFilterState _filter;
        private bool? _isChecked = false;
        internal bool _isLoaded;
        private bool _isThreeState;
        internal const string FilterCheckBoxElementName = "FilterCheckBox";
        public static readonly DependencyProperty FocusBrushProperty = DependencyProperty.Register("FocusBrush", typeof(Brush), typeof(DataGridCheckBoxFilter), null);
        public static readonly DependencyProperty InputBackgroundProperty = DependencyProperty.Register("InputBackground", typeof(Brush), typeof(DataGridCheckBoxFilter), null);
        public static readonly DependencyProperty InputForegroundProperty = DependencyProperty.Register("InputForeground", typeof(Brush), typeof(DataGridCheckBoxFilter), null);
        public static readonly DependencyProperty MouseOverBrushProperty = DependencyProperty.Register("MouseOverBrush", typeof(Brush), typeof(DataGridCheckBoxFilter), null);
        public static readonly DependencyProperty PressedBrushProperty = DependencyProperty.Register("PressedBrush", typeof(Brush), typeof(DataGridCheckBoxFilter), null);

        // Events
        public event EventHandler<PropertyChangedEventArgs<DataGridFilterState>> FilterChanged;

        public event PropertyChangedEventHandler PropertyChanged;

        // Methods
        public DataGridCheckBoxFilter()
        {
            base.DefaultStyleKey = typeof(DataGridCheckBoxFilter);
        }

        public void Clear()
        {
            if (this._isLoaded)
            {
                this.IsChecked = false;
                DataGridFilterState state = this._filter;
                DataGridFilterState state2 = (DataGridFilterState)(this._filter = null);
                if (this.FilterChanged != null)
                {
                    PropertyChangedEventArgs<DataGridFilterState> e = new PropertyChangedEventArgs<DataGridFilterState>
                    {
                        OldValue = state,
                        NewValue = state2
                    };
                    this.FilterChanged(this, e);
                }
            }
        }

        public void Create()
        {
            DataGridFilterState state = this._filter;
            DataGridFilterState filter = this.GetFilter();
            this._filter = filter;
            if (this.FilterChanged != null)
            {
                PropertyChangedEventArgs<DataGridFilterState> e = new PropertyChangedEventArgs<DataGridFilterState>
                {
                    OldValue = state,
                    NewValue = filter
                };
                this.FilterChanged(this, e);
            }
        }

        protected virtual DataGridFilterState GetFilter()
        {
            if (this.IsChecked.HasValue || this.IsThreeState)
            {
                DataGridFilterInfo info = new DataGridFilterInfo
                {
                    Value = this.IsChecked.HasValue ? this.IsChecked.Value : false,
                    FilterOperation = DataGridFilterOperation.Equal,
                    FilterCombination = DataGridFilterCombination.None,
                    FilterType = DataGridFilterType.CheckBox
                };
                return new DataGridFilterState { FilterInfo = new List<DataGridFilterInfo>(1) { info } };
            }
            return null;
        }

        private T GetTemplateChild<T>(string childName, bool required, ref string errors) where T : class
        {
            DependencyObject templateChild = base.GetTemplateChild(childName);
            ApplyTemplateHelper.VerifyTemplateChild(typeof(T), "template part", childName, templateChild, required, ref errors);
            return (templateChild as T);
        }

        private static Storyboard GetTemplateChildResource(FrameworkElement root, string resourceName, bool required, ref string errors)
        {
            return GetTemplateChildResource<Storyboard>(root, resourceName, required, ref errors);
        }

        private static T GetTemplateChildResource<T>(FrameworkElement root, string resourceName, bool required, ref string errors) where T : class
        {
            object child = root.Resources[resourceName];
            ApplyTemplateHelper.VerifyTemplateChild(typeof(T), "resource", resourceName, child, required, ref errors);
            return (child as T);
        }

        public void Load(DataGridFilterState filterState)
        {
            this.SetFilter(filterState);
        }

        private void OnAfterApplyTemplate()
        {
            this._elementFilterCheckBox.SetBinding(ToggleButton.IsThreeStateProperty, new Binding().From<DataGridCheckBoxFilter>(this, x => x.IsThreeState));
            Binding binding = new Binding
            {
                Mode = BindingMode.TwoWay
            };
            this._elementFilterCheckBox.SetBinding(ToggleButton.IsCheckedProperty, binding.From<DataGridCheckBoxFilter>(this, x => x.IsChecked));
        }

        public override void OnApplyTemplate()
        {
            string errors = string.Empty;
            base.OnApplyTemplate();
            this._isLoaded = true;
            this._elementFilterCheckBox = this.GetTemplateChild<CheckBox>("FilterCheckBox", true, ref errors);
            if (!string.IsNullOrEmpty(errors))
            {
                this._isLoaded = false;
                if ((base.Template != null) && !PlatformIndependent.IsInDesignMode(this))
                {
                    throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, "Template cannot be applied to DataGridCheckBoxFilter.\nDetails: {0}", new object[] { errors }));
                }
            }
            else
            {
                this.OnAfterApplyTemplate();
            }
        }

        protected void RaisePropertyChanged(string propertyName)
        {
            if (this.PropertyChanged != null)
            {
                this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }

        protected virtual void SetFilter(DataGridFilterState filterState)
        {
            if (((filterState != null) && (filterState.FilterInfo != null)) && ((filterState.FilterInfo.Count > 0) && (filterState.FilterInfo[0] != null)))
            {
                this._isChecked = filterState.FilterInfo[0].Value as bool?;
                this._filter = this.GetFilter();
            }
            else
            {
                this._isChecked = false;
                this._filter = null;
            }
            this.RaisePropertyChanged("IsChecked");
            this.RaisePropertyChanged("Filter");
        }

        // Properties
        public DataGridFilterState Filter
        {
            get
            {
                return this._filter;
            }
            set
            {
                if (this._filter != value)
                {
                    this._filter = value;
                    this.SetFilter(value);
                }
            }
        }

        public Brush FocusBrush
        {
            get
            {
                return (Brush)base.GetValue(FocusBrushProperty);
            }
            set
            {
                base.SetValue(FocusBrushProperty, value);
            }
        }

        public Brush InputBackground
        {
            get
            {
                return (Brush)base.GetValue(InputBackgroundProperty);
            }
            set
            {
                base.SetValue(InputBackgroundProperty, value);
            }
        }

        public Brush InputForeground
        {
            get
            {
                return (Brush)base.GetValue(InputForegroundProperty);
            }
            set
            {
                base.SetValue(InputForegroundProperty, value);
            }
        }

        public bool? IsChecked
        {
            get
            {
                return this._isChecked;
            }
            set
            {
                this._isChecked = value;
                this._filter = this.GetFilter();
                this.RaisePropertyChanged("IsChecked");
                this.RaisePropertyChanged("Filter");
            }
        }

        public bool IsThreeState
        {
            get
            {
                return this._isThreeState;
            }
            set
            {
                this._isThreeState = value;
                this.RaisePropertyChanged("IsThreeState");
            }
        }

        public Brush MouseOverBrush
        {
            get
            {
                return (Brush)base.GetValue(MouseOverBrushProperty);
            }
            set
            {
                base.SetValue(MouseOverBrushProperty, value);
            }
        }

        public Brush PressedBrush
        {
            get
            {
                return (Brush)base.GetValue(PressedBrushProperty);
            }
            set
            {
                base.SetValue(PressedBrushProperty, value);
            }
        }
    }
}
